from apps.users.models import User
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import Group
from rest_framework import serializers


class AdminUserModelSerializer(ModelSerializer):
    """管理员序列化器"""

    password=serializers.CharField(write_only=True, required=False)#write_only表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
    class Meta:
        model=User
        fields=('id','username','email','mobile','password','groups','user_permissions')


    def create(self, validated_data):

        pwd=validated_data.pop('password')
        user=super().create(validated_data)
        user.set_password(pwd)
        user.is_staff=True
        user.save()

        return user

    def update(self, instance, validated_data):
        try:
            pwd = validated_data.pop('password')
        except KeyError:
            user=super().update(instance,validated_data)
            user.is_staff=True
            user.save()
        else:
            user=super().update(instance,validated_data)
            user.set_password(pwd)
            user.is_staff=True
            user.save()

        return user

class GroupModelSerializer(ModelSerializer):
    """权限组序列化器"""

    class Meta:
        model=Group
        fields='__all__'

